import 'package:fl_chart/fl_chart.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/config.dart';
import 'package:sleep/provider/db_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/wave_provider.dart';
import 'package:sleep/single/analyze/sleep_analyze.dart';
import 'package:sleep/single/wave_show_model.dart';

class SleepDetailWave {
  final String rr; //呼吸频率
  final String t1; //间隔时间
  final String at; //呼吸暂停时间
  final String ri; //呼吸强度
  final String rt; //实时数据
  final String ht; //实时数据
  final List<FlSpot> prSpots;
  final List<FlSpot> t1Spots;
  final List<FlSpot> atSpots;
  final List<FlSpot> riSpots;
  final List<FlSpot> htSpots;
  final SleepShowData? wave;
  final List<SleepShowData> waves;

  SleepDetailWave(
      {required this.rr,
      required this.ht,
      required this.htSpots,
      required this.t1,
      required this.ri,
      required this.at,
      required this.rt,
      required this.wave,
      required this.waves,
      required this.prSpots,
      required this.atSpots,
      required this.t1Spots,
      required this.riSpots});
}

final sleepDetailProvider = Provider<SleepDetailWave>((ref) {
  final sleep = ref.watch(sleepProvider);
  final db = ref.read(dbProvider);

  final analyze = sleep.analyze as SleepAnalyze;
  SleepShowData? wholeWave = analyze.showModel;
  final wholeWaves = analyze.waves;

  final pr = wholeWave?.rr.toStringAsFixed(1) ?? "-";
  final ri = wholeWave?.ri == null
      ? '-'
      : '${wholeWave?.ri.abs().toStringAsFixed(0)}%';
  final t1 = wholeWave?.t1.toStringAsFixed(1) ?? "-";
  final at = wholeWave?.at.toStringAsFixed(1) ?? "-";
  final rt = sleep.rt?.toStringAsFixed(2) ?? "-";
  double htValue = 0;

  final List<FlSpot> prSpots = [];
  final List<FlSpot> t1Spots = [];
  final List<FlSpot> riSpots = [];
  final List<FlSpot> stSpots = [];
  final List<FlSpot> htSpots = [];

  for (int i = 0; i < kDetialShowLengh; i++) {
    final index = wholeWaves.length - i - 1;
    if (index > 0) {
      final current = wholeWaves[index];

      final pr = current.rr;
      final t1 = current.t1;
      final st = current.at;

      final ri = current.ri;

      riSpots.add(FlSpot(i.toDouble(), ri));
      final x = (kDetialShowLengh - i).toDouble();

      prSpots.add(FlSpot(x, pr ?? 0));
      stSpots.add(FlSpot(x, st ?? 0));
      t1Spots.add(FlSpot(x, t1 ?? 0));
    }
  }

  for (int i = 0; i < wholeWaves.length; i++) {
    final current = wholeWaves[i];

    if (current.isLowRi() ?? false) {
      htValue += current.time;
    }
    htSpots.add(FlSpot(i.toDouble(), htValue));
  }

  return SleepDetailWave(
    wave: wholeWave,
    waves: wholeWaves,
    prSpots: prSpots,
    t1Spots: t1Spots,
    riSpots: riSpots,
    atSpots: stSpots,
    htSpots: htSpots,
    at: at,
    ht: htValue.toStringAsFixed(1),
    rr: pr,
    rt: rt,
    t1: t1,
    ri: ri,
  );
});
